package uapp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import uapp.bus.Channel;
import uapp.bus.Message;
import uapp.bus.Subscriber;

public class Application implements Serializable, Channel {

	private static final long serialVersionUID = -380736072423771040L;

	private String id;
	private String name;
	private String description;
	private List<Page> pages;
	private List<Subscriber> subscribers;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getDescription() {
		return description;
	}

	public List<Page> getPages() {
		if (pages == null)
			pages = new ArrayList<Page>();
		for (Page page : pages)
			page.setApplication(this);
		return pages;
	}

	private List<Subscriber> getSubscribers() {
		if (subscribers == null)
			subscribers = new ArrayList<Subscriber>();
		return subscribers;
	}

	public void broadcast(Subscriber subscriber, Message message) {
		for (Subscriber sub : getSubscribers()) {
			if (!sub.equals(subscriber)) {
				for (Class<Message> listeningMessage : sub.getListeningMessages())
					if (listeningMessage.equals(message.getClass()))
						sub.receive(message);
			}
		}
	}

	public void subscribe(Subscriber subscriber) {
		if (!getSubscribers().contains(subscriber))
			getSubscribers().add(subscriber);
	}
}
